package com.letu.core.utils;


import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.ExifInteropDirectory;
import com.drew.metadata.jpeg.JpegReader;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author lyw
 * @Date 2023/3/21 9:14
 */

public class ImageUtil {

    /**
     * 获取图片正确显示需要旋转的角度（顺时针）
     *
     * @param filePath
     * @return
     */
    public static int getRotateAngleForPhoto(String filePath) {
        int angle = 0;
        Metadata metadata;
        try {
            URL url = new URL(filePath);
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            metadata = JpegMetadataReader.readMetadata(inStream);
            Iterable<Directory> directories = metadata.getDirectories();
            metadata.getFirstDirectoryOfType(ExifInteropDirectory.class);
            for (Directory directory : directories) {
                /*System.out.println(directory);
                Collection<Tag> tags = directory.getTags();
                for (Tag tag : tags) {
                    System.out.println(tag.getTagName()+":"+tag.getDescription());
                }
                System.out.println("-----------------------");*/
                if ("Exif IFD0".equals(directory.getName())) {
                    Collection<Tag> tags = directory.getTags();
                    for (Tag tag : tags) {
                        if ("Orientation".equals(tag.getTagName())) {
                            angle = getNum(tag.getDescription());
                            break;
                        }
                    }
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (angle == 0) {
            angle = 1;
        } else if (angle == 90) {
            angle = 6;
        } else if (angle == 270) {
            angle = 8;
        } else if (angle == 180) {
            angle = 3;
        } else {
            angle = 0;
        }
        return angle;
    }

    /**
     * 旋转照片
     *
     * @param fullPath
     * @param angel
     * @return
     */
    public static String rotatePhonePhoto(String fullPath, int angel) {
        BufferedImage src;
        try {
            src = ImageIO.read(new URL(fullPath));
            int src_width = src.getWidth(null);
            int src_height = src.getHeight(null);

            int swidth = src_width;
            int sheight = src_height;

            if (angel == 90 || angel == 270) {
                swidth = src_height;
                sheight = src_width;
            }

            Rectangle rect_des = new Rectangle(new Dimension(swidth, sheight));

            BufferedImage res = new BufferedImage(rect_des.width, rect_des.height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = res.createGraphics();

            g2.translate((rect_des.width - src_width) / 2,
                    (rect_des.height - src_height) / 2);
            g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);

            g2.drawImage(src, null, null);

            ImageIO.write(res, "jpg", new File(fullPath));

        } catch (Exception e) {

            e.printStackTrace();
        }
        return fullPath;
    }


    private static int getNum(String str) {
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        String numStr = m.replaceAll("").trim();
        if (!StringUtils.isBlank(numStr)) {
            return Integer.valueOf(numStr);
        } else {
            return 0;
        }
    }

    /**
     * 处理ios照片
     *
     * @param filePath
     */
    public static void processIosPhotos(String filePath) {
        //计算旋转的角度
        int angle = getRotateAngleForPhoto(filePath);
        if (angle != 0) {
            rotatePhonePhoto(filePath, angle);
        }
    }

    public static void main(String[] args) throws Exception {
//        //不需要旋转
//        //String filePath = "C:\\Users\\51267\\Desktop\\eee (2)\\rotate01.jpg";
//        //需要旋转90度
//        String filePath = "https://builder.ncectj.com:8082/tj-exhibition/img/1679306622500_rotate01.jpg";
////        //需要旋转180度
////        //String filePath = "C:\\Users\\Administrator\\Desktop\\1598182214VTZwNVHf.png";
////        //安卓照片
////        //String filePath = "C:\\Users\\Administrator\\Desktop\\22e2d04abf-6525-4425-b86c-ceacbb2540ab.jpg";
////        int angle = getRotateAngleForPhoto(filePath);
////        System.out.println("旋转角度:" + angle);
////        URL url = new URL(filePath);
////        BufferedImage bufImage = ImageIO.read(url);
////        //BufferedImage bufImage = JpegReader.readImage(new File(filePath));
////        System.out.println("旋转前的宽高:"+bufImage.getWidth()+"*"+bufImage.getHeight());
////        rotatePhonePhoto(filePath,angle);
////        URL url2 = new URL(filePath);
////        BufferedImage bufImage2 = ImageIO.read(url2);
////        //BufferedImage bufImage2 = JpegReader.readImage(new File(filePath));
////        System.out.println("旋转后的宽高:"+bufImage2.getWidth()+"*"+bufImage2.getHeight());
//
//
//        URL url = new URL(filePath);
//        URLConnection conn = url.openConnection();
//        InputStream inStream = conn.getInputStream();
//        Metadata metadata = JpegMetadataReader.readMetadata(inStream);
//        Iterable<Directory> directories = metadata.getDirectories();
//        metadata.getFirstDirectoryOfType(ExifInteropDirectory.class);
//        for (Directory directory : directories) {
//                /*System.out.println(directory);
//                Collection<Tag> tags = directory.getTags();
//                for (Tag tag : tags) {
//                    System.out.println(tag.getTagName()+":"+tag.getDescription());
//                }
//                System.out.println("-----------------------");*/
//            if ("Exif IFD0".equals(directory.getName())) {
//                Collection<Tag> tags = directory.getTags();
//                for (Tag tag : tags) {
//                    if ("Orientation".equals(tag.getTagName())) {
//                        System.out.println(tag);
//                    }
//                }
//                break;
//            }
//        }


        getRotateAngleForPhoto("https://minio.itgiec.com/pvenue/WJ564060581066080256.png");
    }


}
